package com.guass.nettyprotostuff.rpc.client;

import com.guass.nettyprotostuff.common.RpcUtils;
import com.guass.nettyprotostuff.rpc.MsgDecoder;
import com.guass.nettyprotostuff.rpc.MsgEncoder;
import com.guass.nettyprotostuff.rpc.common.TypeData;
import com.guass.nettyprotostuff.zookeeper.ZookeeperService;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.SplittableRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author guass
 * @date 2022年07月19日 17:04
 */
@Slf4j
public class ClientTest implements IClient{

    private Bootstrap bootstrap;

    protected String serverIp = "127.0.0.1";

    private int startPort;

    private int endPort;

    private ZookeeperService zookeeperService;


    public ClientTest(String serverIp,ZookeeperService zookeeperService){
        this.serverIp = serverIp;
        this.zookeeperService = zookeeperService;
    }

    @Override
    public void start() {


    }

    @Override
    public void start(int num, int beginPort, int nPort) {

        this.startPort = beginPort;
        this.endPort = nPort;

        NioEventLoopGroup group = new NioEventLoopGroup();

        NettyClientHandler nettyClientHandler = new NettyClientHandler(this);

        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ByteBuf byteBuf = Unpooled.copiedBuffer(TypeData.DELIMITER.getBytes());

                        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf))
                                .addLast(new MsgDecoder())
                                .addLast(new MsgEncoder())
                                .addLast( new IdleStateHandler(0, 0, RpcUtils.rand(360,540), TimeUnit.SECONDS))
                                .addLast(nettyClientHandler);
                    }
                });

        doConnectTest(num, beginPort, nPort);
    }

    protected void doConnectTest(final int num,final int beginPort, int nPort) {

        for (int i = 0; i < num; i++) {
            int connectPort = beginPort + i % (nPort - beginPort);
            doConnect(serverIp,connectPort);
        }
    }

    @Override
    public void doConnect(String serverIp, int port) {

        log.info("guass test ===> {},{}",serverIp, port);
        ChannelFuture channelFuture = bootstrap.connect(serverIp, port);

        //实现监听通道连接的方法
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            if(channelFuture1.isSuccess()){
                Channel channel = channelFuture1.channel();

            }else{
                log.info("每隔2s重连....");
                channelFuture1.channel().eventLoop().schedule(() -> {
                    // TODO Auto-generated method stub
                   reConnect(serverIp, port);

                },2, TimeUnit.SECONDS);
            }
        });
    }

    @Override
    public void reConnect(String serverIp, int port) {
        doConnect(zookeeperService.getServerIp(), port);
    }

    @Override
    public ConnectInfo getConnectInfo() {

        ConnectInfo connectInfo = new ConnectInfo();
        connectInfo.setServerIp(serverIp);

        SplittableRandom splittableRandom = new SplittableRandom();
        int nextPort = splittableRandom.nextInt(startPort, endPort - 1);

        connectInfo.setPort(nextPort);

        return connectInfo;
    }
}
